#!/bin/bash
#
# Build DEB package for T-One Agent
#
export PS4='[${FUNCNAME}@${BASH_SOURCE}:${LINENO}|${SECONDS}]+ '

TONE_AGENT_GIT_URL="https://gitee.com/anolis/tone-agent.git"
TONE_AGENT_LOCAL_DIR="/root/tone-agent"
GOLANG_VERSION="1.18.5"
GOLANG_DEVHOME="https://go.dev/dl"

function golang_setenv
{
    if which go > /dev/null; then
        echo "Nice, go is already installed."
    else
        echo "Oops, go is not installed." >&2
        echo "Please download go${GOLANG_VERSION}.linux-<ARCH>.tar.gz" >&2
        echo "from ${GOLANG_DEVHOME} and install it manually." >&2
        exit 1
    fi

    go env -w CGO_ENABLED=0
    go env -w GO111MODULE=on
    go env -w GOPROXY=https://goproxy.cn,direct
}

function clone_toneagent
{
    typeset version=${1?"***version"}

    rm -rf ${TONE_AGENT_LOCAL_DIR}
    git clone --single-branch --branch v${version} ${TONE_AGENT_GIT_URL} ${TONE_AGENT_LOCAL_DIR}
    rm -rf ${TONE_AGENT_LOCAL_DIR}/.git
}

function build_pkg_on_debian
{
    typeset version=${1?"***version"}
    typeset arch=$(dpkg-architecture -q DEB_HOST_ARCH)

    sudo apt-get update
    sudo apt-get install -y dpkg-dev

    pushd $(pwd -P)
    cd ${TONE_AGENT_LOCAL_DIR}
    GOOS=linux GOARCH=${arch} go build -o toneagent
    popd

    cp -r ${TONE_AGENT_LOCAL_DIR}/build/toneagent .
    mkdir -p toneagent/usr/bin
    mkdir -p toneagent/usr/lib/systemd/system
    cp ${TONE_AGENT_LOCAL_DIR}/toneagent toneagent/usr/bin/toneagent
    cp ${TONE_AGENT_LOCAL_DIR}/build/toneagent.service toneagent/usr/lib/systemd/system/toneagent.service
    sed -i "s/Version: .*-/Version: ${version}/" toneagent/DEBIAN/control
    chmod -R 755 toneagent

    dpkg -b toneagent/ toneagent-${version}-${arch}.deb
}

trap "rm -rf ${TONE_AGENT_LOCAL_DIR}" EXIT
version=${1:-"2.0.10"}
golang_setenv
clone_toneagent ${version}
build_pkg_on_debian ${version}
